<template>
    <el-row class="cdetail-row">
        <el-col :span="24">
            <el-card class="box-card tinfo-head-box">
                <div slot="header" class="clearfix">
                    <div class="tinfo-title-header-box" style="background-image:url('/static/img/illustration/i004.jpg')">
                    </div>
                </div>
                <el-row class="user-title-row">
                    <el-col :span="24">
                        <div class="T-headImage-box">
                            <div class="T-headImage">
                                <img src="/static/img/userImage.png" alt="">
                            </div>
                        </div>
                        <div class="T-name-box">
                            <h3>{{courseData.name}}</h3>
                        </div>
                        <div class="clear"></div>
                    </el-col>
                </el-row>
            </el-card>
        </el-col>
        <el-col :span="24">
            <el-card class="box-card">
                <div slot="header" class="clearfix">
                    <span>目录</span>
                    <div style="float: right">
                        <el-button type="primary" size="mini" @click="handleAdd(1)">新增章</el-button>
                    </div>
                </div>
                <div>
                    <el-tree
                            class="filter-tree"
                            :data="treeData"
                            :props="defaultProps"
                            :expand-on-click-node="false"
                            :default-expanded-keys="[1,1]"
                            :filter-node-method="filterNode"
                            @node-click='toArticlePage'>
						 <span class="custom-tree-node" slot-scope="{node, data }">
							 <span>{{ node.label }}</span>
							 <span class="btn-box deleted-btn">
								 <el-button
                                         v-if="node.level === 1 "
                                         type="text"
                                         size="mini"
                                         @click="handleAdd(2, node)">
									 添加节
								 </el-button>
								 <el-button
                                         v-if="node.level === 2 "
                                         type="text"
                                         size="mini"
                                         @click="handleAdd(3, node)">
									 添加知识点
								 </el-button>
							 </span>
						 </span>
                    </el-tree>
                </div>
                <!--新增界面-->
                <el-dialog class="cdetail-dialog" title="新增知识点" :visible.sync="addFormVisible" :close-on-click-modal="false">
                    <el-form v-show="showDialogType===1" label-width="80px"  ref="editForm">
                        <el-form-item label="章节-章">
                            <el-input v-model="SN1Name" type="text" placeholder="请输入章节-章名称"></el-input>
                        </el-form-item>
                        <el-form-item label="第几章">
                            <el-select v-model="SN1Index" placeholder="请选择此章节是第几章">
                                <el-option
                                        v-for="o in treeData.length+1"
                                        :key="o"
                                        :label="'第 '+ o +' 章'"
                                        :value="o">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                    <el-form v-show="showDialogType===2" label-width="80px"  ref="editForm">
                        <el-form-item label="章节-章">
                            <el-input v-model="SN2SN1Name" disabled="" type="text" placeholder="请输入章节-章名称"></el-input>
                        </el-form-item>
                        <el-form-item label="章节-节">
                            <el-input v-model="SN2Name" type="text" placeholder="请输入章节-章名称"></el-input>
                        </el-form-item>
                        <el-form-item label="第几节">
                            <el-select v-model="SN2Index" placeholder="请选择此章节是第几章">
                                <el-option
                                        v-for="o in SN2SN1ChildNum"
                                        :key="o"
                                        :label="'第 '+ o +' 节'"
                                        :value="o">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                    <el-form v-show="showDialogType===3" label-width="80px"  ref="editForm">
                        <el-form-item label="章节-章">
                            <el-input v-model="SN3SN1Name" disabled="" type="text" placeholder="请输入章节-章名称"></el-input>
                        </el-form-item>
                        <el-form-item label="章节-节">
                            <el-input v-model="SN3SN2Name" disabled="" type="text" placeholder="请输入章节-章名称"></el-input>
                        </el-form-item>
                        <el-form-item label="知识点">
                            <el-input v-model="SN3Name" type="text" placeholder="请输入章节-章名称"></el-input>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button  size="small" @click.native="addFormVisible = false">取消</el-button>
                        <el-button type="primary"  size="small" @click.native="saveSubmit()" :loading="saveLoading">提交</el-button>
                    </div>
                </el-dialog>

            </el-card>
        </el-col>
    </el-row>
</template>

<script>
  import {getSectionStructure,saveSectionData,searchCourseData} from '../../api/api';
  export default {
    data() {
      return {
        courseId: '',
        userName: '',
        userId: '',
        courseData: [],
        datas: [],

        addFormVisible: false,
        saveLoading: false,
        showDialogType: 0,

        treeData: [],
        SN1Name:'',
        SN1Index: '',

        SN2SN1Index: 0,
        SN2SN1Name: '',
        SN2SN1ChildNum: 0,
        SN2Name:'',
        SN2Index: '',

        SN3SN1Index: 0,
        SN3SN1Name: '',
        SN3SN2Index: 0,
        SN3SN2Name:'',
        SN3Name:'',

        defaultProps: {
          children: 'childs',
          label: 'name'
        }
      };
    },

    methods: {
      getData(val1, val2){
        console.log(val1+'\n'+val2);
        let para = {
          courseId: val2,
          teacherId: val1,
        };
        getSectionStructure(para).then((res) => {
          console.log(res);
          if(res.data.data.length > 0){
            this.datas = res.data.data[0];
            this.treeData = res.data.data[0].childs
          }
        });
      },

      getCourseData(val){
        searchCourseData(val).then((res) => {
          console.log(res);
          this.courseData = res.data.data;
        });
      },

      remove(node, data) {
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(d => d.id === data.id);
        children.splice(index, 1);
      },

      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },

      toArticlePage(val){
        if(val.hasOwnProperty('childs')){
        }else{
          this.$router.push({path:'/article?a='+val.nodeId})
        }
      },

      handleAdd: function(val,node){
        this.showDialogType = val;
        this.addFormVisible = true;
        this.SN1Name = '';
        this.SN1Index = '';
        if(val === 2){
          this.SN2SN1Index = '';
          this.SN2SN1Name = '';
          this.SN2SN1ChildNum = '';
          this.SN2Name = '';
          this.SN2Index = '';
          this.SN2SN1Index = node.parent.data.findIndex(d => d.nodeId === node.data.nodeId);
          this.SN2SN1Name = node.data.name;
          this.SN2SN1ChildNum = node.data.childs.length + 1;
        }else if(val === 3){
          this.SN3SN1Index = '';
          this.SN3SN1Name = '';
          this.SN3SN2Index = '';
          this.SN3SN2Name = '';
          this.SN3Name = '';
          this.SN3SN1Index = node.parent.parent.data.findIndex(d => d.nodeId === node.parent.data.nodeId);
          this.SN3SN2Index = node.parent.data.childs.findIndex(d => d.nodeId === node.data.nodeId);
          this.SN3SN1Name = node.parent.data.name;
          this.SN3SN2Name = node.data.name;
        }
      },

      randomString() {
        let newDate = new Date();
        let newTime = newDate.getTime().toString();
        let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
        let maxPos = $chars.length;
        let val = '';
        for (let i = 0; i < 10; i++) {
          val += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return newTime.substring(8)+this.userId.substring(12)+val;
      },


      saveSubmit:function () {
        let jsonStr;
        let nodeId = this.randomString();
        console.log(nodeId);
        if(this.datas.length === 0){
          jsonStr = {
            courseId: '',
            courseName: '',
            teacherId: '',
            teacherName: '',
            childs: [
            ]
          };
          jsonStr.teacherId = this.userId;
          jsonStr.teacherName = this.userName;
          jsonStr.courseId = this.courseData.id;
          jsonStr.courseName = this.courseData.name;
          console.log(this.SN1Index);
          this.treeData.splice(this.SN1Index - 1,0,{
            nodeId: nodeId,
            name: this.SN1Name,
            childs: []
          });
          jsonStr.childs = this.treeData;
          console.log(1)
        }else{
          let dataArr;
          jsonStr = JSON.parse(JSON.stringify(this.datas));
          dataArr = JSON.parse(JSON.stringify(this.treeData));
          if(this.showDialogType === 1){
            dataArr.splice(this.SN1Index - 1,0,{
              nodeId: nodeId,
              name: this.SN1Name,
              childs: []
            })
          }else if(this.showDialogType === 2){
            dataArr[this.SN2SN1Index].childs.splice(this.SN2Index - 1,0,{
              nodeId: nodeId,
              name: this.SN2Name,
              childs: []
            })
          }else if(this.showDialogType === 3){
            dataArr[this.SN3SN1Index].childs[this.SN3SN2Index].childs.push({
              nodeId: nodeId,
              name: this.SN3Name,
            })
          }
          jsonStr.childs = dataArr;
        }
        this.saveLoading = true;
        console.log(jsonStr);
        saveSectionData(jsonStr).then((res) => {
          console.log(res);
          this.saveLoading = false;
          this.addFormVisible = false;
          this.SN1Name = '';
          this.SN1Index = '';
          this.SN2SN1Index = '';
          this.SN2SN1Name = '';
          this.SN2SN1ChildNum = '';
          this.SN2Name = '';
          this.SN2Index = '';
          this.SN3SN1Index = '';
          this.SN3SN1Name = '';
          this.SN3SN2Index = '';
          this.SN3SN2Name = '';
          this.SN3Name = '';
          this.getData(this.userId,this.courseData.id);
        });
      }
    },

    mounted: function () {
      function GetRequest() {
        let url = decodeURI(location.search);
        let theRequest = new Object();
        if (url.indexOf("?") != -1) {
          let str = url.substr(1);
          let strs = str.split("&");
          for(let i = 0; i < strs.length; i ++) {
            theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
          }
        }
        return theRequest;
      }
      let urlData = GetRequest();
      this.getCourseData(urlData.c);


      let user = sessionStorage.getItem('user');
      user = JSON.parse(user);

      this.userId = user.id;
      this.userName = user.name;

      this.getData(user.id, urlData.c)
    }
  };
</script>